package com.cheer.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.common.Page;
import com.cheer.dao.OaArticleDao;
import com.cheer.dto.OaArticleAddDTO;
import com.cheer.dto.OaArticleUpdateDTO;
import com.cheer.entity.OaArticleClassEntity;
import com.cheer.entity.OaArticleEntity;
import com.cheer.enums.OaIntegralRuleEnum;
import com.cheer.exception.ServiceException;
import com.cheer.service.OaArticleClassService;
import com.cheer.service.OaArticleService;
import com.cheer.service.OaIntegralService;
import com.cheer.service.SystemConfigService;
import com.cheer.vo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("oaArticleService")
public class OaArticleServiceImpl extends ServiceImpl<OaArticleDao, OaArticleEntity> implements OaArticleService {

    @Value("${image.url}")
    private String imageUrl;

    @Autowired
    private OaArticleDao oaArticleDao;

    @Autowired
    private OaArticleClassService oaArticleClassService;

    @Autowired
    private OaIntegralService oaIntegralService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Override
    @Transactional
    public void add(OaArticleAddDTO articleAddDTO) {
        if (articleAddDTO.getSort() == null || articleAddDTO.getSort() <= 0) {
            articleAddDTO.setSort(1);
        }

        oaArticleDao.incrSort(articleAddDTO.getSort());

        OaArticleEntity article = new OaArticleEntity()
                .setTitle(articleAddDTO.getTitle())
                .setMoreImg(StringUtils.join(articleAddDTO.getMoreImg(), ","))
                .setOneImg(articleAddDTO.getOneImg())
                .setImgUrl(articleAddDTO.getImgUrl())
                .setSource(articleAddDTO.getSource())
                .setDescribe(articleAddDTO.getDescribe())
                .setContent(articleAddDTO.getContent())
                .setHref(articleAddDTO.getHref())
                .setArticleClass(articleAddDTO.getArticleClass())
                .setSort(articleAddDTO.getSort())
                .setTime(articleAddDTO.getTime());

        if (articleAddDTO.getAddTime() == null) {
            article.setAddTime(String.valueOf(DateUtil.currentSeconds()));
        } else {
            article.setAddTime(String.valueOf((articleAddDTO.getAddTime().getTime() / 1000)));
        }

        oaArticleDao.insert(article);
    }

    @Override
    public Page<OaArticleListVO> list(Integer pageNum, Integer pageSize, Integer articleClass, String title, Integer id) {
        IPage<OaArticleEntity> page = oaArticleDao.selectPageByArticleClass(pageNum, pageSize, articleClass, title, id);

        List<OaArticleListVO> articleListVOList = page.getRecords().stream()
                .map(article -> new OaArticleListVO()
                        .setId(article.getId())
                        .setTitle(article.getTitle())
                        .setSort(article.getSort())
                        .setImgUrl(imageUrl + article.getOneImg())
                        .setArticleClass(article.getArticleClass())
                        .setHref(article.getHref())
                        .setStatus(article.getStatus())
                        .setRecommend(article.getRecommend())
                        .setAddTime(StringUtils.isBlank(article.getAddTime()) ? "" : DateUtil.format(DateUtil.date(
                                Long.valueOf(article.getAddTime()) * 1000), DatePattern.NORM_DATETIME_PATTERN)))
                .collect(Collectors.toList());

        return new Page<>(page, articleListVOList);
    }

    @Override
    @Transactional
    public void delete(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        for (Long id : ids) {
            OaArticleEntity article = oaArticleDao.selectById(id);
            if (article != null) {
                oaArticleDao.deleteById(id);
                oaArticleDao.decrSort(article.getSort());
            }
        }
    }

    @Override
    public OaArticleInfoVO info(Integer id) {
        OaArticleEntity article = oaArticleDao.selectById(id);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }

        OaArticleInfoVO articleInfoVO = new OaArticleInfoVO()
                .setId(article.getId())
                .setTitle(article.getTitle())
                .setSort(article.getSort())
                .setArticleClass(article.getArticleClass())
                .setDescribe(article.getDescribe())
                .setHref(article.getHref())
                .setSource(article.getSource())
                .setTime(article.getTime())
                .setAddTime(StringUtils.isBlank(article.getAddTime()) ? "" : DateUtil.format(DateUtil.date(
                        Long.valueOf(article.getAddTime()) * 1000), DatePattern.NORM_DATETIME_PATTERN))
                .setContent(article.getContent());

        if (StringUtils.isNotBlank(article.getImgUrl())) {
            articleInfoVO.setImgUrl(new ImageVO()
                    .setFullUrl(imageUrl + article.getImgUrl())
                    .setShortUrl(article.getImgUrl()));
        } else {
            articleInfoVO.setImgUrl(new ImageVO()
                    .setFullUrl("")
                    .setShortUrl(""));
        }

        if (StringUtils.isNotBlank(article.getOneImg())) {
            articleInfoVO.setOneImg(new ImageVO()
                    .setFullUrl(imageUrl + article.getOneImg())
                    .setShortUrl(article.getOneImg()));
        } else {
            articleInfoVO.setOneImg(new ImageVO()
                    .setFullUrl("")
                    .setShortUrl(""));
        }

        List<ImageVO> imageVOList = new ArrayList<>();
        String[] split = StringUtils.split(article.getMoreImg(), ",");
        if (ArrayUtils.isNotEmpty(split)) {
            for (String str : split) {
                ImageVO imageVO = new ImageVO()
                        .setFullUrl(imageUrl + str)
                        .setShortUrl(str);
                imageVOList.add(imageVO);
            }
        }
        articleInfoVO.setMoreImg(imageVOList);

        return articleInfoVO;
    }

    @Override
    @Transactional
    public void update(OaArticleUpdateDTO articleUpdateDTO) {
        OaArticleEntity article = oaArticleDao.selectById(articleUpdateDTO.getId());
        if (article == null) {
            throw new ServiceException("文章不存在");
        }

        if (articleUpdateDTO.getSort() != null) {
            if (articleUpdateDTO.getSort() <= 0) {
                articleUpdateDTO.setSort(1);
            }
            if (article.getSort() > articleUpdateDTO.getSort()) {
                oaArticleDao.incrSortRange(articleUpdateDTO.getSort(), article.getSort());
            } else if (article.getSort() < articleUpdateDTO.getSort()) {
                oaArticleDao.decrSortRange(article.getSort(), articleUpdateDTO.getSort());
            }
        }

        OaArticleEntity updateArticle = new OaArticleEntity()
                .setId(articleUpdateDTO.getId())
                .setTitle(articleUpdateDTO.getTitle())
                .setMoreImg(StringUtils.join(articleUpdateDTO.getMoreImg(), ","))
                .setOneImg(articleUpdateDTO.getOneImg())
                .setImgUrl(articleUpdateDTO.getImgUrl())
                .setDescribe(articleUpdateDTO.getDescribe())
                .setContent(articleUpdateDTO.getContent())
                .setHref(articleUpdateDTO.getHref())
                .setArticleClass(articleUpdateDTO.getArticleClass())
                .setSort(articleUpdateDTO.getSort())
                .setTime(articleUpdateDTO.getTime());

        if (articleUpdateDTO.getAddTime() != null) {
            article.setAddTime(String.valueOf((articleUpdateDTO.getAddTime().getTime() / 1000)));
        }

        oaArticleDao.updateById(updateArticle);
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        OaArticleEntity article = oaArticleDao.selectById(id);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }

        OaArticleEntity updateArticle = new OaArticleEntity()
                .setId(article.getId())
                .setStatus(status);

        oaArticleDao.updateById(updateArticle);
    }

    @Override
    public void updateRecommend(Integer id, Integer recommend) {
        OaArticleEntity article = oaArticleDao.selectById(id);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }

        OaArticleEntity updateArticle = new OaArticleEntity()
                .setId(article.getId())
                .setRecommend(recommend);

        oaArticleDao.updateById(updateArticle);
    }

    @Override
    public List<OaArticleSimpleVO> listRecommend(Integer pageNum, Integer pageSize) {
        List<OaArticleEntity> articleList = oaArticleDao.selectListByRecommend(pageNum, pageSize);

        return articleList.stream()
                .map(oaArticleEntity -> {
                    OaArticleSimpleVO oaArticleSimpleVO = new OaArticleSimpleVO()
                            .setId((long) oaArticleEntity.getId())
                            .setName(oaArticleEntity.getTitle())
                            .setSource(oaArticleEntity.getSource())
                            .setTime(DateUtil.format(DateUtil.date(Long.valueOf(oaArticleEntity.getAddTime()) * 1000),
                                    DatePattern.NORM_DATE_PATTERN));
                    if (StringUtils.isNotBlank(oaArticleEntity.getOneImg())) {
                        oaArticleSimpleVO.setImgUrl(imageUrl + oaArticleEntity.getOneImg());
                    } else if (StringUtils.isNotBlank(oaArticleEntity.getImgUrl())) {
                        oaArticleSimpleVO.setImgUrl(imageUrl + oaArticleEntity.getImgUrl());
                    } else {
                        String[] split = StringUtils.split(oaArticleEntity.getMoreImg(), ",");
                        if (ArrayUtils.isNotEmpty(split)) {
                            oaArticleSimpleVO.setImgUrl(imageUrl + split[0]);
                        }
                    }
                    return oaArticleSimpleVO;
                })
                .collect(Collectors.toList());
    }

    @Override
    public OaArticleClassFrontVO listByArticleClass(Integer articleClass) {
        OaArticleClassFrontVO articleClassFrontVO = new OaArticleClassFrontVO();

        OaArticleClassEntity articleClassEntity = oaArticleClassService.getByUsed(articleClass);
        if (articleClassEntity != null) {
            if (StringUtils.isNotBlank(articleClassEntity.getImgUrl())) {
                articleClassFrontVO.setImgUrl(imageUrl + articleClassEntity.getImgUrl());
            }
            articleClassFrontVO.setArticleId(articleClassEntity.getArticleId());
        }

        List<OaArticleEntity> articleList = oaArticleDao.selectListByArticleClassLimit(0, 10, articleClass);
        articleClassFrontVO.setArticleList(articleList.stream()
                .map(oaArticleEntity -> {
                    OaArticleFrontVO oaArticleFrontVO = new OaArticleFrontVO()
                            .setId((oaArticleEntity.getId()))
                            .setTitle(oaArticleEntity.getTitle())
                            .setSource(oaArticleEntity.getSource())
                            .setTime(DateUtil.format(DateUtil.date(Long.valueOf(oaArticleEntity.getAddTime()) * 1000),
                                    DatePattern.NORM_DATE_PATTERN));
                    if (StringUtils.isNotBlank(oaArticleEntity.getOneImg())) {
                        oaArticleFrontVO.setImgUrl(imageUrl + oaArticleEntity.getOneImg());
                    } else if (StringUtils.isNotBlank(oaArticleEntity.getImgUrl())) {
                        oaArticleFrontVO.setImgUrl(imageUrl + oaArticleEntity.getImgUrl());
                    } else {
                        String[] split = StringUtils.split(oaArticleEntity.getMoreImg(), ",");
                        if (ArrayUtils.isNotEmpty(split)) {
                            oaArticleFrontVO.setImgUrl(imageUrl + split[0]);
                        }
                    }
                    return oaArticleFrontVO;
                })
                .collect(Collectors.toList()));

        return articleClassFrontVO;
    }

    @Override
    public List<OaArticleFrontVO> listByArticleClass(Integer pageNum, Integer pageSize, Integer articleClass) {
        int start = (pageNum - 1) * pageSize;
        int offset = pageSize;

        List<OaArticleEntity> articleList = oaArticleDao.selectListByArticleClassLimit(start, offset, articleClass);

        return articleList.stream()
                .map(oaArticleEntity -> {
                    OaArticleFrontVO oaArticleFrontVO = new OaArticleFrontVO()
                            .setId((oaArticleEntity.getId()))
                            .setTitle(oaArticleEntity.getTitle())
                            .setSource(oaArticleEntity.getSource())
                            .setTime(StringUtils.isBlank(oaArticleEntity.getAddTime())? "" : DateUtil.format(DateUtil.date(Long.valueOf(oaArticleEntity.getAddTime()) * 1000),
                                    DatePattern.NORM_DATE_PATTERN));
                    if (StringUtils.isNotBlank(oaArticleEntity.getOneImg())) {
                        oaArticleFrontVO.setImgUrl(imageUrl + oaArticleEntity.getOneImg());
                    } else if (StringUtils.isNotBlank(oaArticleEntity.getImgUrl())) {
                        oaArticleFrontVO.setImgUrl(imageUrl + oaArticleEntity.getImgUrl());
                    } else {
                        String[] split = StringUtils.split(oaArticleEntity.getMoreImg(), ",");
                        if (ArrayUtils.isNotEmpty(split)) {
                            oaArticleFrontVO.setImgUrl(imageUrl + split[0]);
                        }
                    }
                    return oaArticleFrontVO;
                })
                .collect(Collectors.toList());
    }

    @Override
    public String getTitle(Integer id) {
        String title = oaArticleDao.selectTitleById(id);
        if (title == null) {
            return "";
        }
        return title;
    }

    @Override
    public String enter(Integer id, Integer userId, String openid) {
        String url = oaArticleDao.selectHrefById(id);

        OaArticleEntity articleEntity = oaArticleDao.selectById(id);
        Integer articleClassId = articleEntity.getArticleClass();

        if(articleClassId.equals(OaIntegralRuleEnum.ARTICLE_PIC_ID)){
            oaIntegralService.add(userId, openid, OaIntegralRuleEnum.ARTICLE_PIC, id);
        }else if(articleClassId.equals(OaIntegralRuleEnum.ARTICLE_WIN_ID)){
            oaIntegralService.add(userId, openid, OaIntegralRuleEnum.ARTICLE_WIN, id);
        }else{
            oaIntegralService.add(userId, openid, OaIntegralRuleEnum.ARTICLE, id);
        }
        return url;
    }

    @Override
    public List<SimpleObjectVO> all() {
        List<OaArticleEntity> articleEntities = oaArticleDao.selectListByOrder();
        return articleEntities.stream()
                .map(article -> new SimpleObjectVO()
                        .setId(Long.valueOf(article.getId()))
                        .setName(article.getTitle()))
                .collect(Collectors.toList());
    }

    @Override
    public List<SimpleObjectVO> listSimpleByArticleClass(Integer articleClass) {
        List<OaArticleEntity> articleEntities = oaArticleDao.selectListByArticleClassAndOrder(articleClass);
        return articleEntities.stream()
                .map(article -> new SimpleObjectVO()
                        .setId(Long.valueOf(article.getId()))
                        .setName(article.getTitle()))
                .collect(Collectors.toList());
    }

    @Override
    public OaArticleEntity getFirst(Integer articleClass) {
        return oaArticleDao.getFirst(articleClass);
    }
}